package com.jd.finance.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jd.finance.core.mapper.*;
import com.jd.finance.core.pojo.dto.*;
import com.jd.finance.core.pojo.entity.*;
import com.jd.finance.core.service.LoanService;
import com.jd.finance.result.BaseResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 贷款表 服务实现类
 * </p>
 *
 * @author LiQingBo
 * @since 2022-05-17
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class LoanServiceImpl extends ServiceImpl<LoanMapper, Loan> implements LoanService {

    @Autowired
    private LoanMapper loanMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private BankCardMapper bankCardMapper;

    @Autowired
    private CompanyMapper companyMapper;

    @Resource
    private AdminUtilsServiceImpl adminUtilsService;
    @Resource
    private LoanApplyMapper loanApplyMapper;


    @Resource
    private LoanService loanService;

    /**
     * 查询审核通过，待签约的产品
     *
     * @param uid
     * @return
     */
    @Override
    public BaseResult getExamPassed(Integer uid) {
        if (uid == null) {
            log.error("查询审核通过，待签约的产品,信息为空！ Service");
            return BaseResult.error().message("信息为空");
        }
        List<ProductInfoDTO> sigList = loanMapper.selectSigList(uid);
        return BaseResult.ok().data("list", sigList);
    }

    // 28 接口 未定义
    // /**
    //  * 根据uid查询待还款产品
    //  *
    //  * @param uid
    //  * @return
    //  */
    // @Override
    // public BaseResult getRepayProd(Integer uid) {
    //     if (uid == null) {
    //         log.error("根据uid查询待还款产品,用户信息为空 S" );
    //         return BaseResult.error().message("用户信息为空");
    //     }
    //     List<RepayProdListDTO> repayProdList = loanMapper.getRepayProd(uid);
    //     return BaseResult.ok().data("list", repayProdList);
    // }

    /**
     * 查询贷款记录
     *
     * @param uid
     * @return
     */
    @Override
    public BaseResult selectLonInfo(Integer uid) {
        List<LoanInfoDTO> loanList = loanMapper.selectLoanInfo(uid);
        if (loanList == null || loanList.size() == 0) {
            return BaseResult.error().message("未查询到贷款记录!");
        }
        QueryWrapper<Company> companyQueryWrapper = new QueryWrapper<>();
        companyQueryWrapper.eq("uid", uid);
        List<Company> companyList = companyMapper.selectList(companyQueryWrapper);
        if (companyList == null && companyList.size() == 0) {
            for (LoanInfoDTO loanInfoDTO : loanList) {
                loanInfoDTO.setCompName("");
            }
        }
        return BaseResult.ok().data("loans", loanList);
    }


    /**
     * 查询平台交易人数
     *
     * @return
     */
    @Override
    public BaseResult getTradeUserCount() {
        QueryWrapper<Loan> loanQueryWrapper = new QueryWrapper<>();
        loanQueryWrapper.select("DISTINCT uid");
        int count = loanMapper.selectCount(loanQueryWrapper);

        if (count == 0) {
            return BaseResult.error().message("未查询到交易人数！");
        }
        return BaseResult.ok().data("jiaoyiPerson", count);
    }

    /**
     * 获取当月贷款申请金额总数
     *
     * @param uid
     * @return
     */
    @Override
    public BaseResult getCityYearSumMoney(Integer uid) {
        if (uid == null) {
            log.error("id为空!");
            return BaseResult.error().message("id为空");
        }
        List<YearMoneyDTO> yearMoneyDTOS = loanMapper.selectYearMoney();
        return BaseResult.ok().data("list:", yearMoneyDTOS);
    }

    /**
     * 查询年度流水按月
     *
     * @param uid     登录管理员id
     * @param request
     * @return 每个月份流水
     */
    @Override
    public BaseResult getRunWater(Integer uid, HttpServletRequest request) {
        if (uid == null) {
            log.error("id为空");
            return BaseResult.error().message("id为空");
        }
        if (adminUtilsService.isGM(uid)) {
            log.error("无访问权限");
            return BaseResult.ok().message("无访问权限");
        }

        List<LoanRunWaterDTO> loanRunWaterDTOList = loanMapper.getRunWater();

        return BaseResult.ok().data("list", loanRunWaterDTOList);
    }


    /**
     * 根据uid查询当月业绩总额
     *
     * @param gmId 总经理id
     * @param uid  工作人员id
     * @return
     */
    @Override
    public BaseResult getSumKpiMonth(Integer gmId, Integer uid) {
        if (gmId == null || uid == null) {
            log.error("根据uid获取当月业绩汇总,提交信息为空!");
            return BaseResult.error().message("根据uid获取当月业绩汇总,提交信息为空!");
        }

        if (!adminUtilsService.isGM(gmId)) {
            log.error("登录用户非总经理身份!");
            return BaseResult.error().message("登录用户非总经理身份!");
        }

        if (!adminUtilsService.isSale(uid)) {
            log.error("该用户非业务员身份!");
            return BaseResult.error().message("该用户非业务员身份!");
        }

        QueryWrapper<Loan> loanQueryWrapper = new QueryWrapper<>();
        loanQueryWrapper.eq("worker_id", uid);
        List<Loan> list = loanMapper.selectList(loanQueryWrapper);

        if (list.size() == 0 || list == null) {
            log.error("未查询到相关业绩数据!");
            return BaseResult.error().message("未查询到相关业绩数据!");
        }
        BigDecimal mouthSum = loanMapper.getSumKpiMonth(uid);
        Map<String, Object> result = new HashMap<>();
        result.put("uid", uid);
        result.put("allyjmon", mouthSum);
        return BaseResult.ok().data(result);
    }

    /**
     * 根据uid获取当年业绩汇总
     *
     * @param gmId 总经理id
     * @param uid  业务员id
     * @return
     */
    @Override
    public BaseResult getSumKpiYear(Integer gmId, Integer uid) {
        if (gmId == null || uid == null) {
            log.error("根据uid获取当月业绩汇总,提交信息为空!");
            return BaseResult.error().message("根据uid获取当月业绩汇总,提交信息为空!");
        }

        if (!adminUtilsService.isGM(gmId)) {
            log.error("登录用户非总经理身份!");
            return BaseResult.error().message("登录用户非总经理身份!");
        }

        if (!adminUtilsService.isSale(uid)) {
            log.error("该用户非业务员身份!");
            return BaseResult.error().message("该用户非业务员身份!");
        }

        QueryWrapper<Loan> loanQueryWrapper = new QueryWrapper<>();
        loanQueryWrapper.eq("worker_id", uid);
        List<Loan> list = loanMapper.selectList(loanQueryWrapper);

        if (list.size() == 0 || list == null) {
            log.error("未查询到相关业绩数据!");
            return BaseResult.error().message("未查询到相关业绩数据!");
        }

        BigDecimal yearSum = loanMapper.getSumKpiYear(uid);
        Map<String, Object> result = new HashMap<>();
        result.put("uid", uid);
        result.put("allyjyear", yearSum);
        return BaseResult.ok().data(result);

    }

    /**
     * 总经理查询 当年业绩前三名
     *
     * @param uid 总经理id
     * @return
     */
    @Override
    public BaseResult getKpiYearTopThree(Integer uid) {
        if (uid == null) {
            log.error("总经理查询当年业绩前三名,提交信息为空!");
            return BaseResult.error().message("总经理查询当年业绩前三名,提交信息为空!");
        }

        if (!adminUtilsService.isGM(uid)) {
            log.error("登录用户非总经理身份!");
            return BaseResult.error().message("登录用户非总经理身份!");
        }
        List<GetKpiYearTopThreeDTO> list = loanMapper.getKpiYearTopThree();
        if (list == null || list.size() == 0) {
            log.error("未查询到当年业绩前三名!");
            return BaseResult.error().message("未查询到当年业绩前三名!");
        }

        return BaseResult.ok().data("topThreeList", list);
    }

    /**
     * 根据银行id及月份，查询成交的产品信息
     *
     * @param uid    总经理id
     * @param bid    银行id
     * @param monthT 月份
     * @return
     */
    @Override
    public BaseResult getTradeInfo(Integer uid, Integer bid, Integer monthT) {
        if (uid == null || bid == null || monthT == null) {
            log.error("根据银行id，以及月份，获取指定月份该银行成交的明细，提交信息为空!");
            return BaseResult.error().message("根据银行id，以及月份，获取指定月份该银行成交的明细，提交信息为空!");
        }

        if (!adminUtilsService.isGM(uid)) {
            log.error("该用户非总经理身份!");
            return BaseResult.error().message("该用户非总经理身份!");
        }

        QueryWrapper<Loan> loanQueryWrapper = new QueryWrapper<>();
        loanQueryWrapper.eq("bid", bid);
        List<Loan> list = loanMapper.selectList(loanQueryWrapper);
        if (list == null || list.size() == 0) {
            log.error("该银行无成交的贷款!");
            return BaseResult.error().message("该银行无成交的贷款!");
        }
        GetTradeInfoDTO getTradeInfoDTO = loanMapper.getTradeInfo(bid, monthT);
        if (getTradeInfoDTO == null) {
            log.error("未查询到相关数据!");
            return BaseResult.error().message("未查询到相关数据!");
        }

        Map<String, Object> result = new HashMap<>();
        result.put("bankid", getTradeInfoDTO.getBankid());
        result.put("monthT", getTradeInfoDTO.getMonthT());
        result.put("bankname", getTradeInfoDTO.getBankname());
        result.put("productInfo", getTradeInfoDTO.getBankTradeProductDTOS());
        return BaseResult.ok().data("getTradeInfo", result);
    }


    /**
     * 进行中的贷款列表（分页，每页6条）
     *
     * @param page
     * @param limit
     * @param uid
     * @return
     */
    @Override
    public BaseResult getTradingLoanList(Long page, Long limit, Integer uid) {
        if (uid == null) {
            log.error("传入id为空");
        }
        if (adminUtilsService.isAdmin(uid)) {
            log.error("无访问权限");
            return BaseResult.error().message("无访问权限");
        }

        List<GetTradingLoanListDTO> getTradingLoanListDTOList = loanMapper.getTradingLoanList((page - 1) * limit, limit);
        return BaseResult.ok().data("list", getTradingLoanListDTOList);
    }

    /**
     * 根据银行id，获取同一个银行所有信贷员列表（不分页，根据业绩正序排序）
     *
     * @param bid 银行id
     * @return
     */
    @Override
    public BaseResult getLoanOfficerInfo(Integer bid) {
        if (bid == null) {
            log.error("银行id为空");
            return BaseResult.error().message("银行id为空");
        }
        List<GetLoanOfficerInfoDTO> loanOfficerInfo = loanMapper.getLoanOfficerInfo(bid);
        Map<String, Object> result = new HashMap<>();
        result.put("bankid", bid);
        result.put("xdylist", loanOfficerInfo);
        return BaseResult.ok().data(result);
    }

    /**
     * 重新申请贷款，就在之前的贷款申请数据上修改，更新基本字段，审核字段清空，返回是否成功
     *
     * @param lid        贷款申请id
     * @param uid        贷款人id
     * @param workId     工作人员id
     * @param bcId       卡号id
     * @param proName    产品名
     * @param bankName   银行名称
     * @param loanReason 贷款原因
     * @param loanMoney  贷款金额
     * @param allDebt    整体负债
     * @return 修改结果
     */
    @Override
    public BaseResult secondLoanApply(Integer lid, Integer uid, Integer workId,
                                      Integer bcId, String proName,
                                      String bankName, String loanReason,
                                      BigDecimal loanMoney, BigDecimal allDebt) {
        if (lid == null) {
            log.error("传入参数为空");
            return BaseResult.error().message("传入参数为空");
        }

        //对数据进行修改
        UpdateWrapper<LoanApply> lup = new UpdateWrapper<>();
        lup.lambda().eq(LoanApply::getLoanAppId, lid)
                .set(uid != null, LoanApply::getUid, uid)
                .set(!StringUtils.isBlank(proName), LoanApply::getProName, proName)
                .set(workId != null, LoanApply::getWorkerId, workId)
                .set(!StringUtils.isBlank(bankName), LoanApply::getBankName, bankName)
                .set(bcId!= null, LoanApply::getBcId, bcId)
                .set( loanMoney != null, LoanApply::getLoanMoney, loanMoney)
                .set(!StringUtils.isBlank(loanReason), LoanApply::getLoanReason, loanReason)
                .set(allDebt!=null, LoanApply::getTotalDebt, allDebt)
            // 设置审核信息为空
                .set(LoanApply::getLoanApplyStatus,"待审核")
                .set(LoanApply::getCheckFirst,null)
                .set(LoanApply::getCheckSecond,null)
                .set(LoanApply::getIsPassFirst,0)
                .set(LoanApply::getIsPassSecond,0)
                .set(LoanApply::getMessageFirst,null)
                .set(LoanApply::getMessageSecond,null)
                .set(LoanApply::getCheckerFirstId,null)
                .set(LoanApply::getCheckerSecondId,null)
                .set(LoanApply::getCheckerFirstName,null)
                .set(LoanApply::getCheckerSecondName,null)
                .set(LoanApply::getTop,null)
                .set(LoanApply::getTopRate,null);
        int update = loanApplyMapper.update(null, lup);
        if (update >= 1) {
            return BaseResult.ok().data("xiugaijg", 1);
        } else {
            return BaseResult.ok().data("xiugaijg", 0);
        }

    }

    /**
     * 查询平台交易额
     * @return
     */
    @Override
    public BigDecimal findDealCount() {
        QueryWrapper<Loan> qw = new QueryWrapper<>();
        qw.select("IFNULL(sum(loan_money),0) as loanMoney");
        Loan loan = loanMapper.selectOne(qw);
        BigDecimal loanMoney = loan.getLoanMoney();
        if (loanMoney == null) {
            Integer count = 0;
            return new BigDecimal(Integer.parseInt(String.valueOf(count)));
        }
        return loanMoney;
    }
}
